/*
 * 加载完后执行
 */
$(function () {
    const Base_Url = "http://127.0.0.1:8080/";
    const searchBut = $("#searchBut");
    const createBut = $("#createBut");
    const cancelBut = $("#cancelBut");
    const pushBut = $("#pushBut");
    const editBut = $("#editBut");
    const pageSize = 10;
    let nowPageNum = 1;
    let dataList = {};
    let promotionId = null;
    /**
     * 格式化时间
     **/
    const formatDatatimeStr =(str)=>{
        return str.replace("T"," ").replace(".000+00:00","");
    }
    /**
     *设置数据
     **/
    const setTableList = (list) => {
        let html = ""
        const getTD = (v) => {
            return "<td>" + (v || "") + "</td>";
        }
        list.forEach((v, i) => {
            html += "<tr>";
            html += getTD(i + 1);
            html += getTD(v.promotionName);
            html += getTD(formatDatatimeStr(v.startTime) + "\n至\n" + formatDatatimeStr(v.endTime));
            html += getTD(v.pushContents);
            html += getTD(v.pushMobile);
            html += getTD(v.pushStatus ? "成功" : (v.pushStatus == null ? "发送中" : "失败"));
            html += getTD(v.errorMessage);
            if (v.pushStatus == null) {
                html += getTD("");
            } else {
                html += getTD("<button type='button'   class='del'  promotionId='" + v.promotionId + "' >删除</button><button type='button' class='edit'    promotionId='" + v.promotionId + "' >修改</button><button type='button' class='retransmit'    promotionId='" + v.promotionId + "' >重发</button>");

            }
            html += "</tr>";
            dataList[v.promotionId] = v;
        });
        $("#list tr:gt(0)").remove();
        $("#list").append(html);
    };

    /**
     *设置页目条
     * isFirst 是否是首页
     * isLast 是否是尾页
     * nowPage 当前页
     * totalPages 总页数
     **/
    const setPageBar = (isFirst, isLast, nowPage, totalPages) => {
        nowPageNum = nowPage + 1;

        let startPageNum = nowPageNum - 2;
        startPageNum = startPageNum < 1 ? 1 : startPageNum;


        let endPageNum = startPageNum + 4;
        endPageNum = endPageNum > totalPages ? totalPages : endPageNum;

        let html = "";
        if (!isFirst) {
            html += "<span page='1'>&lt;&lt;</span><span page='" + (nowPageNum - 1) + "'>&lt;</span>";
        }
        for (; startPageNum <= endPageNum; startPageNum++) {
            html += "<span page='" + startPageNum + "' class='" + (startPageNum == nowPageNum ? "selected" : "") + "'>" + startPageNum + "</span>";
        }
        if (!isLast) {
            html += "<span page='" + (nowPageNum + 1) + "'>&gt;</span><span  page='" + totalPages + "'>&gt;&gt;</span>";
        }
        $("#pagelist").html(html);
    }

    /**
     *查询
     * param pageNum 页数
     **/
    const search = (pageNum) => {
        const promotionName = $("#promotionNameSearch").val();
        const pushMobile = $("#pushMobileSearch").val();
        $.post(Base_Url + "promotion/listSearch", {
            promotionName: promotionName,
            pushMobile: pushMobile,
            page: pageNum - 1,
            size: pageSize
        }, (data) => {
            if (data.status == "S") {
                setTableList(data.data.content);
                setPageBar(data.data.first, data.data.last, data.data.number, data.data.totalPages);
            } else {
                alert(data.sysMsg)
            }
        });
    };
    searchBut.on("click", () => {
        search(1)
    });

    /**
     * 打开窗口-新建
     **/
    const openWin = () => {
        $("#promotionName").val("");
        $("#startTime").val("");
        $("#endTime").val("");
        $("#pushContents").val("");
        $("#pushMobile").val("");
        $("#pushContents").css({border:"1px solid #767676"});
        $("#pushContents").removeAttr("readonly");
        editBut.hide();
        pushBut.show();
        $("#win").show();

    }

    /**
     * 打开窗口-修改
     **/
    const openWin_Edit = (data) => {
        promotionId = data.promotionId;
        $("#promotionName").val(data.promotionName);
        $("#startTime").val(formatDatatimeStr(data.startTime));
        $("#endTime").val(formatDatatimeStr(data.endTime));
        $("#pushContents").val(data.pushContents);
        $("#pushContents").css({border:"none"});
        $("#pushContents").attr("readonly","readonly");
        $("#pushMobile").val(data.pushMobile.split(",").join("\n"));
        editBut.show();
        pushBut.hide();
        $("#win").show();
    }

    /**
     * 关闭窗口
     **/
    const closeWin = () => {
        $("#win").hide();
    }
    createBut.on("click", openWin);
    cancelBut.on("click", closeWin);
    $(document).on("click",".edit", function(){
        let promotionId = $(this).attr("promotionId");
        openWin_Edit(dataList[promotionId]);
    });

    // 验证手机号
    const isPhoneNo = (phone) => {
        return /^1[34578]\d{9}$/.test(phone);
    }
    /**
     *新建活动
     **/
    pushBut.on("click", () => {
        let promotionName = $("#promotionName").val();
        let startTime = $("#startTime").val();
        let endTime = $("#endTime").val();
        let pushContents = $("#pushContents").val();
        let pushMobile = $("#pushMobile").val();
        pushMobile = pushMobile.split("\n");

        let errorPhone = [];
        pushMobile.forEach(function (t) {
            t = $.trim(t);
            if (!isPhoneNo(t)) {
                errorPhone.push(t);
            }
        });
        if (errorPhone.length > 0) {
            alert("以下手机号码格式错误：" + errorPhone.join(","));
            return;
        }
        if (pushMobile.length > 100) {
            alert("最多支持100个号码，多号码时以回车键换行分隔");
            return;
        }

        if (pushContents.length == 0) {
            alert("推送内容不能为空");
            return;
        }

        if (startTime.length == 0) {
            alert("活动开始时间不能为空");
            return;
        }
        if (endTime.length == 0) {
            alert("活动结束时间不能为空");
            return;
        }


        $.post(Base_Url + "promotion/save", {
            promotionName: promotionName,
            startTime: startTime,
            endTime: endTime,
            pushContents: pushContents,
            pushMobile: pushMobile.join(",")
        }, (d) => {
            if (d.status == "S") {
                search(1);
                closeWin();
            }
            alert(d.sysMsg);
        });

    });
    /**
     *绑定修改
     **/
    editBut.on("click", () => {
        let promotionName = $("#promotionName").val();
        let startTime = $("#startTime").val();
        let endTime = $("#endTime").val();
        let pushContents = $("#pushContents").val();
        let pushMobile = $("#pushMobile").val();
        pushMobile = pushMobile.split("\n");

        let errorPhone = [];
        pushMobile.forEach(function (t) {
            t = $.trim(t);
            if (!isPhoneNo(t)) {
                errorPhone.push(t);
            }
        });
        if (errorPhone.length > 0) {
            alert("以下手机号码格式错误：" + errorPhone.join(","));
            return;
        }
        if (pushMobile.length > 100) {
            alert("最多支持100个号码，多号码时以回车键换行分隔");
            return;
        }

        if (pushContents.length == 0) {
            alert("推送内容不能为空");
            return;
        }

        if (startTime.length == 0) {
            alert("活动开始时间不能为空");
            return;
        }
        if (endTime.length == 0) {
            alert("活动结束时间不能为空");
            return;
        }


        $.post(Base_Url + "promotion/update", {
            promotionName: promotionName,
            promotionId: promotionId,
            startTime: startTime,
            endTime: endTime,
            pushContents: pushContents,
            pushMobile: pushMobile.join(",")
        }, (d) => {
            if (d.status == "S") {
                search(nowPageNum);
                closeWin();
            }
            alert(d.sysMsg);
        });
    });

    /**
     *绑定删除
     **/
    $(document).on('click', '.del', function () {
        if (window.confirm("确定要删除此活动?")) {
            let promotionId = $(this).attr("promotionId");
            $.post(Base_Url + "promotion/delete", {promotionId: promotionId}, function (data) {
                if (data.status == "S") {
                    search(nowPageNum);
                    closeWin();
                } else {
                    alert(data.sysMsg);
                }
            });
        }
    });

    /**
     *重发
     **/
    $(document).on('click', '.retransmit', function () {
        if (window.confirm("确定要重发此活动")) {
            let promotionId = $(this).attr("promotionId");
            $.post(Base_Url + "promotion/pushPromotion", {promotionId: promotionId}, function (data) {
                if (data.status == "S") {
                    search(nowPageNum);
                }
                alert(data.sysMsg);
            });
        }
    });


    search(1)
});
